package org.example.demo21.answer;


import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map.Entry;

/**
 *
 * @author guocong
 * @since 2024/3/14 19:22
 */
public class LruDemo<K, V> {


    private final LinkedHashMap<K, V> cacheMap;

    public LruDemo(int cacheSize){
        /*
         * 最大缓存大小
         */
        cacheMap = new LinkedHashMap<>(16, 0.75F, true) {
            // 就这是关键，自带的删除方法就行，但是需要根据传入值限定大小
            @Override
            protected boolean removeEldestEntry(Entry eldest) {
                return cacheSize + 1 == cacheMap.size();
            }
        };
    }

    /**
     * 放
     *
     * @param key K
     * @param value V
     */
    public void put(K key, V value){
        cacheMap.put(key, value);
    }

    /**
     * 取
     *
     * @param key K
     * @return {@link V}
     */
    public V get(K key){
        return cacheMap.get(key);
    }

    public Collection<Entry<K, V>> getAll(){
        return new ArrayList<>(cacheMap.entrySet());
    }

    public static void main(String[] args) {
        LruDemo<String, Integer> map = new LruDemo<>(3);
        map.put("key1", 1);
        map.put("key2", 2);
        map.put("key3", 3);

        Integer key2 = map.get("key1");
        System.out.println(key2);


        for (Entry<String, Integer> e : map.getAll()){
            System.out.println(e.getKey()+"====>"+e.getValue());
        }
        System.out.println("\n");
        map.put("key4", 4);
        for (Entry<String, Integer> e : map.getAll()){
            System.out.println(e.getKey()+"====>"+e.getValue());
        }
    }

}
